//
//  AudioPlayerManager.swift
//  StarVoiceToText
//
//  Created by 李东 on 2022/8/21.
//

import UIKit
import AVFoundation

class AudioPlayerManager: NSObject {
//    @objc static let shared = AudioPlayerManager()
    
    var playFinish:(() -> Void)?
    var progressDidChange:((CGFloat) -> Void)?
    
    @objc var musicPlayer: AVPlayer?
    var playeItem: AVPlayerItem?
    
    var timer: Timer?
    
    @objc func initPlayers(filePath: String) {
//        let path = SVTBaiDuManager.urlDecodedString(filePath)
//        if path.contains(" ") {
//            path = path.replacingOccurrences(of: " ", with: "%20")
//        }
//        if path.hasChiness() {
//            path = path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
//        }
        musicPlayer = createPlayer(file: filePath)
//        musicPlayer?.delegate = self
//        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(progressHandler), userInfo: nil, repeats: true)
//        RunLoop.main.add(timer!, forMode: .common)
        // 添加监听，当播放到结束时触发
        NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying(_:)), name: .AVPlayerItemDidPlayToEndTime, object: playeItem)
    }
        
    func createPlayer(file: String) -> AVPlayer? {
//        let path = SVTBaiDuManager.urlDecodedString(file)
        var url: URL!
        if file.hasPrefix("http") {
            url = URL(string: file.urlEncoded())
        }else{
            url = URL(fileURLWithPath: file)
        }
        playeItem = AVPlayerItem(url: url)
        try? AVAudioSession.sharedInstance().setCategory(.playback)
        let player = AVPlayer(playerItem: playeItem)
        player.play()
        return player
    }
    
    // 当播放到结束时调用的方法
    @objc func playerDidFinishPlaying(_ notification: Notification) {
        print("音视频播放完毕")
          
        // 移除监听，避免内存泄漏
        NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: playeItem)
         playeItem = nil
        // 这里可以添加其他操作，比如播放下一个音视频等
        playFinish?()
    }
        
    @objc func audioPlay() {
        guard let temp = musicPlayer else {
            return
        }
        temp.play()
    }
    
    @objc func audioPause() {
        guard let temp = musicPlayer else {
            return
        }
        temp.pause()
    }
    
    @objc func audioStop() {
//        guard let temp = musicPlayer else {
//            return
//        }
        musicPlayer?.pause()
        musicPlayer = nil
//        timer?.invalidate()
//        timer = nil
        if playeItem != nil {
            NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: playeItem)
             playeItem = nil
        }
    }
    
    @objc func progressHandler() {
//        guard let temp = musicPlayer else {
//            return
//        }
//        let progrss = CGFloat(temp.currentTime) / CGFloat(temp.duration)
//        progressDidChange?(progrss)
    }
    
    @objc func seet(time: Int) {
//        guard let temp = musicPlayer else {
//            return
//        }
//        temp.currentTime = TimeInterval(time)
    }
}

extension AudioPlayerManager: AVAudioPlayerDelegate {
    //播放结束
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        playFinish?()
    }
    
    
}
